import {
  Card,
  Tree,
  Col,
  Row,
  Tag,
  Pagination,
  Table,
  Button,
  message,
} from "antd"
import type { TreeProps } from "antd/lib/tree"
import { useEffect, useState } from "react"
import { useNavigate, useParams } from "react-router-dom"
// 引入接口函数
import {
  reqGetDepartmentList,
  reqGetHospitalRuleTags,
  reqGetHosScheduleList,
} from "@/api/hospital/hospitalLists"
// 引入接口类型
import {
  DepartmentList,
  bookingScheduleList,
  IHosScheduleList,
} from "@/api/hospital/model/hospitalListsType"

export default function HospitalSchedule() {
  // 设置用于保存 医院科室 的状态
  const [departmentList, setDepartmentList] = useState<DepartmentList>([])
  // 设置用于保存 二级医院科室 的状态
  const [depcodeList, setDepcodeList] = useState<DepartmentList>([])
  // 设置用于保存 医院排班日期 的状态
  const [tags, setTags] = useState<bookingScheduleList[]>([])
  // 设置用于保存 医院排班列表 的状态
  const [workDataList, setWorkDataList] = useState<IHosScheduleList>([])
  // 设置保存 分页器 数据
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(20)
  // 设置用于保存 title-name 数据
  const [hosname, setHosname] = useState("")
  const [depname, setDepname] = useState("")
  const [workData, setWorkData] = useState("")
  // 用于保存 depcode 数值
  let depcode = "200040878"
  //获取查询字符串
  const { hoscode } = useParams()
  //设置 navigate 对象
  const navigate = useNavigate()

  useEffect(() => {
    async function fetchData() {
      // 获取医院科室
      const res = await getDepartmentList()
      depcode = res[0].children ? res[0].children[0].depcode : ""
      // 获取医院排班日期
      const res1 = await getTags(page, pageSize, depcode)
      const workData = res1.bookingScheduleList[0].workDate
      // 获取医院排班列表
      getScheduleList(workData)
    }
    fetchData()
  }, [])

  //获取 医院科室 数据的函数
  async function getDepartmentList() {
    const result = await reqGetDepartmentList(hoscode as string)
    result.map((item) => (item.disabled = true))
    setDepartmentList(result)
    // 设置医院科室一级菜单展开
    setDepcodeList(result.map((item) => item.depcode) as any)
    // 保存医院科室名称
    setDepname(result[0].children[0].depname)
    return result
  }
  //获取 医院排班日期 数据的函数
  async function getTags(page: any, pageSize: any, depcode: string) {
    // 调用获取 医院排班 的函数
    const result = await reqGetHospitalRuleTags({
      page,
      pageSize,
      hoscode: hoscode as string,
      depcode,
    })
    setTags(result.bookingScheduleList)
    // 保存医院名称
    setHosname(result.baseMap.hosname)
    setTotal(result.total)
    return result
  }
  //获取 医院排班列表 数据的函数
  async function getScheduleList(workDate: string) {
    // 调用获取 医院排班 的函数
    const result = await reqGetHosScheduleList(
      hoscode as string,
      depcode,
      workDate
    )
    setWorkDataList(result)
    // 保存医院排班日期
    setWorkData(result[0].workDate)
    return result
  }

  const onSelect: TreeProps["onSelect"] = (selectedKeys, info) => {
    // console.log("selectedKeys", selectedKeys, info)
    async function fetchData() {
      try {
        setDepname((info.node as any).depname)
        depcode = selectedKeys[0] as string
        const res = await getTags(page, pageSize, selectedKeys[0] as string)
        setWorkData(res.bookingScheduleList[0].workDate)
        getScheduleList(res.bookingScheduleList[0].workDate)
      } catch (error) {
        message.error("暂无数据")
        setTags([])
        setWorkDataList([])
        setWorkData("")
      }
    }
    fetchData()
  }

  //计算 左侧导航栏 的自适应 高
  const treeHeight =
    document.documentElement.clientHeight - 64 - 24 * 2 - 22 - 14 - 5

  //设置表格表头
  const columns = [
    {
      title: "序号",
      render: (a: any, b: any, index: number) => {
        return index + 1
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费(元)",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ]

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workData}
      </p>
      <Row gutter={20}>
        {/* 医院科室渲染 */}
        <Col span={5}>
          <div
            style={{
              height: treeHeight,
              border: "1px solid silver",
              overflow: "auto",
            }}>
            <Tree
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
              onSelect={onSelect}
              treeData={departmentList as []}
              expandedKeys={depcodeList as any}
            />
          </div>
        </Col>
        <Col span={19}>
          {/* 医院排班渲染 */}
          {tags.map((item, index) => {
            return (
              <Tag
                color={workData === item.workDate ? "green" : ""}
                style={{ marginBottom: 10, cursor: "pointer" }}
                key={index}
                onClick={() => {
                  async function fetchData() {
                    getScheduleList(item.workDate)
                    setWorkData(item.workDate)
                  }
                  fetchData()
                }}>
                <div>
                  {item.workDate} {item.dayOfWeek}
                </div>
                <div>
                  {item.availableNumber} / {item.reservedNumber}
                </div>
              </Tag>
            )
          })}
          {/* 分页器渲染 */}
          <Pagination
            defaultCurrent={1}
            current={page}
            pageSize={pageSize}
            total={total}
            style={{ marginBottom: 10 }}
            showSizeChanger={true}
            pageSizeOptions={[2, 5, 10]}
            onChange={async (page: number, pageSize: number) => {
              setPage(page)
              setPageSize(pageSize)
              const res = await getTags(page, pageSize, depcode)
              setWorkData(res.bookingScheduleList[0].workDate)
              getScheduleList(res.bookingScheduleList[0].workDate)
            }}
          />
          {/* 表格渲染 */}
          <Table
            // 设置表格格式
            columns={columns}
            // 添加表格要渲染的数据
            dataSource={workDataList}
            // 给表格主体没行设置key
            rowKey="id"
            // 设置表格的内边框
            bordered={true}
            // 设置表格分页器隐藏
            pagination={false}
          />
          <Button
            style={{ marginTop: 10 }}
            onClick={() => {
              navigate(-1)
            }}>
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  )
}
